using IQIGame.Onigao.Framework;
using IQIGame.Onigao.GamePlay;

namespace IQIGame.Onigao.Logic
{
    /// <summary>
    /// 自动寻路到目标点
    /// 参数组1：1实体tag（填0表示自己，只支持单个），2：导航过程中是否无须等待英雄（0：等待（默认），1不等待）(可选)
    /// 参数组2：路径（xyz循环）
    /// </summary>
    public class ExecAutoNavigation : BaseServiceExecution
    {
        public override void Execute(LevelRegion region, LevelPlayer player)
        {
            var config = _config as ExecParamAutoNavigation;
            if (!config.tagOrMcid.TryGetValue(triggerEntity, out int tagOrMcid))
            {
                LogicLog.LogError("无法获取到tagOrMcid.");
                return;
            }
            bool needWaitHero = config.needWaitHero;
            LevelEntity entity = tagOrMcid == 0 ? triggerEntity : region.GetEntityByTagOrMcid(tagOrMcid);
            if (entity == null)
            {
                LogicLog.LogError($"根据TagOrMcid[{tagOrMcid}]找不到任何实体。");
                return;
            }

            LogicLevelMoveParam[] posList = new LogicLevelMoveParam[config.pos.Count];
            for (int i = 0; i < config.pos.Count; i++)
            {
                Vector3Int pos = config.pos[i];
                var moveParam = new LogicLevelMoveParam();
                moveParam.destination = pos;
                moveParam.speedRatio = 1;
                posList[i] = moveParam;
            }

#if UNITY_EDITOR
            LgNpcNavAssistantComponent tempNavCom = entity.GetComponent<LgNpcNavAssistantComponent>();
            if (tempNavCom != null)
            {
                LogicLog.LogError($"寻路失败，当前有寻路还未完成。");
                return;
            }
#endif

            //寻路，添加成功后行为树会进入正常寻路状态，寻路结束后，行为树会移除寻路辅助组件
            LgNpcNavAssistantComponent navHelper = entity.AddComponent<LgNpcNavAssistantComponent>();
            navHelper.TryStartNav(posList, needWaitHero, true, true, true);
        }
    }
}
